
#include "rpi_radar_cmd.h"

#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <poll.h>

#include <stdio.h>
#include <errno.h>
#include <inttypes.h>

static void read_radar(int fd)
{
	int ret;
	struct pollfd pfd = {.fd = fd, .events = POLLIN};
	ret = poll(&pfd, 1, 1000);
	if (ret > 0 && pfd.revents == POLLIN)
	{
		int64_t elapsed = 0;
		ret = read(fd, &elapsed, sizeof(elapsed));
		if (ret > 0)
		{
			/* 直接读取的值是超声波往返时间，按 340m/s 的声速进行计算 */
			printf("radar range, %lldcm\n", (elapsed * 340) / 20000);
		}
	}

	return;
}

int main(int argc, char *argv[])
{
	int cmd = RPI_RADAR_CMD_START;
	if (argc > 1)
	{
		cmd = RPI_RADAR_CMD(atoi(argv[1]));
	}
	printf("radar cmd: %X\n", cmd);

    int fd = open("/dev/rpi_radar", O_RDWR);
    if (fd > 0)
    {
        ioctl(fd, cmd, NULL);
		
		if (cmd == RPI_RADAR_CMD_START)
		{
			read_radar(fd);
		}

        close(fd);
    }
	else
	{
		printf("rpi_radar open failed, errno: %d\n", errno);
	}
    
    return 0;
}